package com.ruoyi.web.controller.tool;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import me.chanjar.weixin.common.error.WxErrorException;

@RestController
@RequestMapping("/wxApi")
public class WxApi {
    // 微信小程序的appid
    @Value("${wx.wxappid}")
    private String wxappid;

    // 微信小程序的appid
    @Value("${wx.wxsecret}")
    private String wxsecret;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private ISysMenuService sysMenuService;
    
    @PostMapping("/applogin")
    public AjaxResult applogin(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();

            WxMaService wxService = getWxMaService();
            //解密手机号
            WxMaPhoneNumberInfo wxMaPhoneNumberInfo = wxService.getUserService().getPhoneNoInfo(loginBody.getSessionkey(), loginBody.getEncryptedData(), loginBody.getIv());
            if (null==wxMaPhoneNumberInfo|| wxMaPhoneNumberInfo.getPhoneNumber().equals("")) {
                // 解密手机号码信息错误
                ajax=AjaxResult.error("解密手机号码信息错误");
            }else{
                SysUser sysUser=sysUserService.selectUserByUserName(wxMaPhoneNumberInfo.getPhoneNumber());
                if(null==sysUser||null==sysUser.getUserId()){
                    ajax.put("result",false);
                }else{
                    if(null==sysUser.getOpenid()||sysUser.getOpenid().equals("")){//未绑定的不需要进行更新openid
                        sysUser.setOpenid(loginBody.getOpenid());
                        sysUserService.updateUserOpenid(sysUser);
                    }
                    String token = loginService.login(sysUser.getUserName(), "");
                    sysUser.setPermissions(sysMenuService.selectMenuPermsByUserId(sysUser.getUserId()));
                    ajax.put(Constants.TOKEN, token);
                    
                    ajax.put("result",true);
                    ajax.put("userInfo", sysUser);
                }
            }


        return  ajax;
    }
    @GetMapping("/getOpenid")
    public AjaxResult getOpenid(LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        WxMaService wxService = getWxMaService();
        // 获取微信用户session
        WxMaJscode2SessionResult session = null;
        try {
            session = wxService.getUserService().getSessionInfo(loginBody.getCode());
        } catch (WxErrorException wxErrorException) {
            wxErrorException.printStackTrace();
        }
        if (null == session) {
            throw new RuntimeException("login handler error");
        }
        String openid = session.getOpenid();
        String sessionkey =session.getSessionKey();
        ajax.put("openid",openid);
        ajax.put("sessionkey",sessionkey);
        return  ajax;
    }
    private WxMaService getWxMaService() {
        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        String appid=wxappid;
        String secret=wxsecret;
        config.setAppid(appid);
        config.setSecret(secret);
        config.setMsgDataFormat("JSON");
        WxMaService wxMaService = new WxMaServiceImpl();
        wxMaService.setWxMaConfig(config);
        return wxMaService;
    }
}
